package com.all.learning.guava.concurrent.domain;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;

public class AsyncFuntionSample implements AsyncFunction<Long, String>{
	 private ConcurrentMap<Long, String> map = Maps.newConcurrentMap();
	 private ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
	 
	@Override
	public  ListenableFuture<String> apply(final Long input) throws Exception {
		if (map.containsKey(input)) {
            SettableFuture<String> listenableFuture = SettableFuture.create(); //构建一个SettableFuture
            listenableFuture.set(map.get(input));
            return listenableFuture;
        } else {
            return listeningExecutorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    String retrieved = input+""; //compute to get the data;
                    map.putIfAbsent(input, retrieved);
                    return retrieved;
                }
            });
        }
	}

}
